/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Category;
import models.Course;
import models.User;
import org.hibernate.Session;
import service.CategoryDao;
import service.HibernateUtil;
import service.UserDao;

/**
 *
 * @author Aster
 */
public class CategoryController extends HttpServlet {

    private HibernateUtil HU = new HibernateUtil();
    private Session session = HU.openSession();
    private CategoryDao dao = new CategoryDao(session);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        HttpSession sessie = request.getSession(true);

        //haal alle bestaande categoriën op
        try {
            List<Category> categories = dao.findAll();
            sessie.setAttribute("categories", categories);
        } catch (Exception e) {
            System.out.println(e);
        }

        //response.sendRedirect("/categoryManager.jsp");
        forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        Category category = new Category();
        String name = name = request.getParameter("newCat");
        String givenID = request.getParameter("idCat");
        String deleteID = request.getParameter("id2delete");
        
        
        if (givenID != null) {
            Category tempCategory = dao.get(givenID);
            tempCategory.setName(name);
            dao.update(tempCategory);
        } else if (deleteID != null) {
            Category tempCategory = dao.get(deleteID);
            dao.delete(tempCategory);
        } else {
            //nieuwe categorie maken
            Category newCategory = new Category();
            newCategory.setName(name);
            dao.save(newCategory);
        }
        response.sendRedirect("/category");
    }

    private void forward(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String address = "/categoryManager.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
